package cn.wolf.other;

/**
 * 二分查找
 */
public class Search {

    public static int search(int[] arrays, int key) {
        int low = 0;
        int high = arrays.length - 1;
        int middle;

        if (key < arrays[low] || key > arrays[high]) {
            return -1;
        }
        while (low <= high) {
            //有序数组的中间下标,下标将整个数组分为左右两部分
            middle = (low + high) / 2;
            if (arrays[middle] > key) {
                //要查找的数值在数组的右半部分
                high = middle - 1;
            } else if (arrays[middle] < key) {
                low = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arrays = {1, 9, 12, 16, 23, 25, 36, 56, 98, 100};
        int key = 23;
        int middle = search(arrays, key);
        if (middle == -1) {
            System.out.println("查找的数据是" + key + ",序列中没有该数!");
        } else {
            System.out.println("查找的数据是" + key + ",在序列中找到位置为:" + middle);
        }
    }

}
